bky.checkUpdate = function(){
    $.get("http://www.cnblogs.com/liulun/articles/7710391.html",function(r){
        var trueVersion = $(r).find("#51cnblogsVersion").html();
        trueVersion = parseInt($.trim(trueVersion));
        if(bky.version < trueVersion){
            alert("有新版本，您需要升级");
            nw.Shell.openExternal('https://gitee.com/xland/cnblogs/releases');
        }
    })
}
bky.showLogin = function(){
    $("body").append(bky.loginDiv);
    $("#loginFrame").on("load",function(){
        var frame = document.getElementById('loginFrame').contentWindow;
        var testDom = frame.$("#app_ing");
        if(testDom.length > 0 && testDom.html() == "闪存"){
            $("#loginFrame").parent().remove();
        }
    })
}
bky.checkLogin = function(){
    $.get("https://i.cnblogs.com/",function(r){
        var dom = $(r).find("#TabPosts");
        if(dom.length>0 && dom.hasClass("current_nav")){
            return;
        }
        bky.showLogin();
    })
}
bky.editArticleHandler = function(){
    //https://i.cnblogs.com/PostDone.aspx?postid=7681073&actiontip=%e4%bf%9d%e5%ad%98%e4%bf%ae%e6%94%b9%e6%88%90%e5%8a%9f
    var frame = document.getElementById('articleFrame').contentWindow;
    var msg = frame.location.href.split('=');
    msg = msg[msg.length -1];
    msg = decodeURI(msg);
    if(msg == "保存修改成功" || msg == '发布成功'){
        var url = 'https://i.cnblogs.com/'+frame.$("#TipsPanel_LinkEdit").attr("href");
        frame.location.href = url;
        alert("保存成功");
        return;
    }
    setTimeout(function(){
        var title = frame.$("#Editor_Edit_txbTitle").val();
        var content = frame.$('#Editor_Edit_EditorBody').val();
        UE.getEditor('editor').setContent(content);
        $("#titleInput").val(title);
        $("#articleListBg").hide();
    },800);    
}
bky.editArticle = function(){
    $("#articleListWrapper").hide();
    var id = $(this).attr("id");
    $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?postid='+id);
}
bky.newArticle = function(){
    if($("#articleFrame").attr("src") == 'https://i.cnblogs.com/EditPosts.aspx?opt=1'){
        alert("当前已经是新增文章状态");
        return;
    }
    if($("#titleInput").val().length > 0 || UE.getEditor('editor').getContent().length > 0){
        var flag = confirm("您现在处于编辑文章的状态，确实要退出吗？");
        if(!flag){
            return;
        }        
    }
    $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?opt=1');
}
bky.ctrl_v = function(e){
    var clip = nw.Clipboard.get();
    var clipTypes = clip.readAvailableTypes();
    if(clipTypes.length > 0){
        var html = "";
        var type = clipTypes[0];
        if(type == "png"||type == "jpeg"){
            var img = clip.get(type,true);
            var dataBuffer = new Buffer(img, "base64");
            var fn = (new Date()).getTime() + parseInt(1000 * Math.random()) + ".png";
            fs.writeFileSync("logic/files/" + fn, dataBuffer, {encoding: 'base64'});
            html = '<img src="files/' + fn + '" />';
        }else if(type == "text"){
            html = clip.get(type);
            html = html.replace(/\n+/g,"<br />");
        }else{
            html = clip.get(type);
        }
        return html;
    }
}
bky.saveArticle = function(){    
    var obj = {};
    obj.title = $("#titleInput").val();
    obj.content = UE.getEditor('editor').getContent();
    obj.content = '<div class="liulunEditor" style="font-family: Microsoft YaHei;">'+obj.content+'</div>';
    if(obj.title.length < 2||obj.content.length < 6){
        alert("文章标题或者文章正文字数太少");
        return;
    }
    $("#articleListBg").show();
    $("#articleListWrapper").hide();
    var frame = document.getElementById('articleFrame').contentWindow;
    frame.$("#Editor_Edit_txbTitle").val(obj.title);
    //frame.$('#Editor_Edit_EditorBody').val(obj.content);
    //frame.tinyMCE.activeEditor.setContent(obj.content);
    frame.blogEditor.setContent(obj.content);
    //frame.tinyMCE.execCommand('mceInsertContent', false, obj.content);
    frame.$("#Editor_Edit_lkbPost").click();
}
bky.uploadImg = function(event,cb){
    var items = event.clipboardData.items;
    if(items[0].type.indexOf("image") < 0){
        return;
    }
    var file = items[0].getAsFile();
    var formData = new FormData();
    formData.append('imageFile', file);
    formData.append("mimeType", file.type);
    var frame = document.getElementById('articleFrame').contentWindow
    frame.$.ajax({
        type: 'POST',
        url:bky.imgUploadUrl,
        data: formData,
        processData: false, 
        contentType: false, 
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        success: function(result) {
            if(result.success){
                var img = '<img src="' + result.message + '" />';
                cb(img);
            }
        }
    });    
}

bky.getList = function(pageIndex){
    $.get("https://i.cnblogs.com/posts?page="+pageIndex,function(r){
        $("#articleListBg").show();
        var doc = $(r);
        if(!doc.find("#TabPosts")){
            bky.showLogin();
            return;
        }
        var lastPager = doc.find(".pager .current").html();
        if(parseInt(lastPager)<pageIndex){
            return;
        }
        $(".titleRow").remove();        
        doc.find(".post-title a").each(function(index,item){
            var id = $(item).attr("href").split('/');
            id = id[id.length-1]
            id = id.split('.')[0];
            var indexNum = index+1+(pageIndex-1)*30;
            var str = $(item).html();
            str = '<div class="titleRow" id="'+id+'">'+indexNum+':&nbsp;'+str+'</div>';
            if(index < 15){
                $("#articleLeft").append(str);
            }else{
                $("#articleRight").append(str);
            }            
        })
        $(".titleRow").click(bky.editArticle);
        bky.pageIndex = pageIndex;
        $("#articleListWrapper").show();
        
    })
}
$(function(){
    bky.checkUpdate();
    bky.checkLogin();
    var arr = bky.articleDiv.split('^');
    var dom = arr[0]+'https://i.cnblogs.com/EditPosts.aspx?opt=1'+arr[1];    
    $("body").append(dom);
    $("#articleFrame").on("load",bky.editArticleHandler);
})